export default {
  // 为当前模块开启命名空间
  namespaced: true,

  // 模块的 state 数据
  state: () => ({
  cart: uni.getStorageSync('cart') || [] // 购物车商品列表
  }),

  // 模块的 mutations 方法
  mutations: {
    // 持久化数据
    saveToStorage(state){
      uni.setStorageSync('cart', state.cart)
    },
    addToCart(state, goods){
      let f = state.cart.find(t => t.goods_id === goods.goods_id)
      if(f){
        f.goods_count++
      }else{
        state.cart.push(goods)
      }
      this.commit('m_cart/saveToStorage')
    },
    updateGoodsState(state, goods){
      let f = state.cart.find(t => t.goods_id === goods.goods_id)
      if(f){
        f.goods_state = goods.goods_state
        this.commit('m_cart/saveToStorage')
      }
    },
    updateAllGoodsState(state, newState){
      state.cart.forEach(t => {
        t.goods_state = newState
      })
    },
    updateGoodsCount(state, goods){
      let f = state.cart.find(t => t.goods_id === goods.goods_id)
      if(f){
        f.goods_count = goods.goods_count
        this.commit('m_cart/saveToStorage')
      }
    },
    deleteGoods(state, goods){
      let index = state.cart.findIndex(t => t.goods_id === goods.goods_id)
      if(index!== -1){
        state.cart.splice(index, 1)
        this.commit('m_cart/saveToStorage')
      }
    }
  },

  // 模块的 getters 属性
  getters: {
    total(state){
      let result = 0
      state.cart.forEach(t => result += t.goods_count )
      return result
    },
    checkedCount(state){
      // 过滤选中的数据
      // 累加商品数量
      return state.cart.filter(t => t.goods_state).reduce((sum,m) => sum+m.goods_count,0)
    },
    // 选中商品的总价格
    checkedGoodsAmount(state){
      // 选中
      // 统计累加数量单价
      // 保留2位小数
      return state.cart.filter(t => t.goods_state).reduce((sum,m)=>sum+m.goods_count*m.goods_price,0).toFixed(2)
    }
  },
}
